package com.yazi.mxz.mobile.controller.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.constant.RegExp;
import com.yazi.mxz.common.service.MemberService;
import com.yazi.mxz.mobile.common.VerifyAbstractController;
import com.yazi.mxz.mobile.jackson.filter.MemberFilter;


@Controller("user-memberController")
@RequestMapping("/user/member")
public class MemberController extends VerifyAbstractController {
	private static Logger log = LoggerFactory.getLogger(MemberController.class);
	
	@Resource
	MemberService memberService;
	
	@RequestMapping
	public String index(){
		log.debug("进入个人基本信息页面");
		return "v1.5/user/member_info";
	}
	
	@RequestMapping("/info/json")
	@ResponseBody
	public ObjectResult<Member> infoJson(){
		log.debug("获取个人基本信息");
		ObjectResult<Member> jsonResult = new ObjectResult<Member>();
		jsonResult.setFilter(MemberFilter.get4Edit());
		// json
		Member member;
		try{
			member = getMember();
			String email;
			if (null != (email = member.getEmail())) {
				String r = email.substring(3, email.indexOf("@")).replaceAll("[\\S]", "*");
				email = email.substring(0, 3) + r + email.substring(email.indexOf("@"), email.length());
				member.setEmail(email);
			}
			String mobile;
			if (null != (mobile = member.getMobile())) {
				member.setMobile(mobile.substring(0, 3) + "****" + mobile.substring(7, 11));
			}
			jsonResult.setResult(member);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("获取个人基本信息异常：", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/infoDo/json")
	@ResponseBody
	public StatusResult infoDoJson(Member member) {
		log.debug("保存个人基本信息");
		StatusResult jsonResult = new StatusResult();
		try{
			// 禁止在这里修改用户名、手机号和邮箱
			member.setMobile(null);
			member.setEmail(null);
			memberService.editByMember(member, getMember());
			jsonResult.setOkMessage("保存成功");
		} catch (Exception e) {
			log.error("保存个人基本信息异常：", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/account")
	public String account(Model model) {
		log.debug("进入账户安全页面");
		Member member = getMember();
		if (null != member.getMobile()) {
			String mobile = member.getMobile().substring(0, 3) + "****" + member.getMobile().substring(7, 11);
			model.addAttribute("mobile", mobile);
		}
		if (null != member.getEmail()) {
			String email = member.getEmail();
			String r = email.substring(3, email.indexOf("@")).replaceAll("[\\S]", "*");
			email = email.substring(0, 3) + r + email.substring(email.indexOf("@"), email.length());
			model.addAttribute("email", email);
		}
		
		model.addAttribute("member", member);
		return "v1.5/user/member_account";
	}
	
	@RequestMapping("/pwd")
	public String updatePassword() {
		log.debug("进入密码修改页面");
		return "v1.5/user/member_pwd";
	}
	
	@RequestMapping("/checkPwd/json")
	@ResponseBody
	public Map<String, String> checkPwdJson(String oldPwd) {
		log.debug("验证用户旧密码");
		String msg = null;
		Member member = getMember();
		if (!MyUtil.checkPwd(member, oldPwd)) {
			msg = "原密码不正确";
		}
	
		Map<String, String> map = new HashMap<String, String>();
		map.put(null == msg ? "ok" : "error", msg);
		return map;
	}
	
	@RequestMapping("/pwdDo/json")
	@ResponseBody
	public StatusResult pwdDoJson(String oldPwd, String newPwd) {
		log.debug("保存新密码");
		StatusResult jsonResult = new StatusResult();
		Member member;
		try {
			member = getMember();
			if (!MyUtil.checkPwd(member, oldPwd)) {
				jsonResult.setFailMessage("原密码不正确");
				return jsonResult;
			}
			member.setPassword(newPwd);
			MyUtil.encodePwd(member);
			memberService.merge(member);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("修改密码异常:", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	
	/**
	 * 获取手机/邮箱绑定步骤信息.<br>
	 * 信息包括:1.是否已经验证身份;2.可重发短信/邮件剩余时间
	 * @param type 0手机 1邮箱
	 * @return
	 */
	@RequestMapping("/stepInfo/json")
	@ResponseBody
	public ObjectResult<Map<String, Object>> stepInfo(int type) {
		log.debug("获取{}绑定步骤信息", type == 0 ? "手机": "邮箱");
		ObjectResult<Map<String, Object>> jsonResult = new ObjectResult<Map<String, Object>>();
		Map<String, Object> result = new HashMap<String, Object>();
		Captcha cap;
		Long remainTime = 0L;
		if (type == 0) {
			cap = getSmsCaptcha();
			if (null != cap) {
				remainTime = getSmsLag() - (DateUtil.getTimeStamp() - cap.getTimestamp());
			};
		} else {
			cap = getEmailCaptcha();
			if (null != cap) {
				remainTime = getEmailLag() - (DateUtil.getTimeStamp() - cap.getTimestamp());
			};
		}
		result.put("remainTime", remainTime);
		result.put("isVerified", isVerified());
		jsonResult.setResult(result);
		jsonResult.setOk();
		return jsonResult;
	}
	
	
	@RequestMapping("/mobile")
	public String mobile(Model model) {
		log.debug("进入绑定手机页面");
		Captcha cap = getSmsCaptcha();
		if (null != cap) {
			// 下次发送剩余时间
			model.addAttribute("remainTime", getSmsLag() - (DateUtil.getTimeStamp() - cap.getTimestamp()));
		};
		model.addAttribute("isVerified", isVerified());
		return "v1.5/user/member_mobile";
	}
	
	/**
	 * 发送短信验证码
	 * @param mobile
	 * @return
	 */
	@RequestMapping("/sendSms/json")
	@ResponseBody
	public ObjectResult<?> sendSmsJson(String mobile) {
		ObjectResult<Long> jsonResult = new ObjectResult<Long>();
		try {
			if (!mobile.matches(RegExp.MOBILE)) {
				jsonResult.setFailMessage("手机号无效");
				return jsonResult;
			}
			Captcha cap = getSmsCaptcha();
			if (null != cap && (DateUtil.getTimeStamp() - cap.getTimestamp()) < getSmsLag()) {
				jsonResult.setFailMessage("操作太频繁");
				return jsonResult;
			}
			
			// 检查用户是否已经绑定该手机
			if (mobile.equals(getMember().getMobile())) {
				jsonResult.setErrorMessage("手机号不能与原绑定号码相同");
				return jsonResult;
			}
			
			// 检查该手机是否已被使用
			Member member = new Member();
			member.setMobile(mobile);
			List<Member> list = memberService.list(member);
			if (list.size() > 0) {
				jsonResult.setErrorMessage("手机号已被他人使用");
				return jsonResult;
			}
			setCaptchaForMobile(mobile);
			jsonResult.setResult(getSmsLag());
			jsonResult.setOk();
		} catch (MyException e) {
			log.debug("短信验证码发送失败：{}", e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			log.error("短信验证码发送异常：", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/mobileDo/json")
	@ResponseBody
	public StatusResult mobileDoJson(String mobile, String captcha) {
		log.debug("绑定手机");
		StatusResult jsonResult = new StatusResult();
		Member member;
		try {
			if (!checkSmsCaptcha(mobile, captcha)) {
				jsonResult.setErrorMessage("验证码无效");
				return jsonResult;
			}
			member = getMember();
			member.setMobile(mobile);
			memberService.merge(member);
			setVerified(false);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("绑定手机异常：", e);
			jsonResult.setErrorMessage("绑定失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/email")
	public String bindEmail(Model model) {
		log.debug("进入绑定邮箱页面 ");
		Captcha cap = getEmailCaptcha();
		if (null != cap) {
			// 下次发送剩余时间 
			model.addAttribute("remainTime", getEmailLag() - (DateUtil.getTimeStamp() - cap.getTimestamp()));
		}
		model.addAttribute("isVerified", isVerified());
		return "v1.5/user/member_email";
	}
	
	/**
	 * 发送邮箱验证码
	 * @param email
	 * @return
	 */
	@RequestMapping("/sendEmail/json")
	@ResponseBody
	public ObjectResult<?> sendEmailJson(String email) {
		ObjectResult<Long> jsonResult = new ObjectResult<Long>();
		try {
			if (!email.matches(RegExp.EMAIL)) {
				jsonResult.setFailMessage("请输入正确的邮箱地址");
				return jsonResult;
			}
			
			Captcha cap = getEmailCaptcha();
			if (null != cap && (DateUtil.getTimeStamp() - cap.getTimestamp()) < getEmailLag()) {
				jsonResult.setFailMessage("操作太频繁");
				return jsonResult;
			}
			
			// 检查用户是否已经绑定该邮箱
			if (email.equals(getMember().getEmail())) {
				jsonResult.setErrorMessage("邮箱地址不能与原绑定邮箱相同");
				return jsonResult;
			}
			
			// 检查该邮箱是否已被使用
			Member member = new Member();
			member.setEmail(email); 
			List<Member> list = memberService.list(member);
			if (list.size() > 0) {
				jsonResult.setErrorMessage("邮箱地址已被他人使用");
				return jsonResult;
			}
			
			setCaptchaForEmail(member.getName(), email);
			jsonResult.setResult(getEmailLag());
			jsonResult.setOk();
		} catch (MyException e) {
			log.debug("邮件发送验证码失败：{}", e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			log.error("邮件发送验证码异常：", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		
		return jsonResult;
	}
	
	@RequestMapping("/emailDo/json")
	@ResponseBody
	public StatusResult emailDoJson(String email, String captcha) {
		log.debug("绑定邮箱");
		StatusResult jsonResult = new StatusResult();
		Member member;
		try {
			if (!checkEmailCaptcha(email, captcha)) {
				jsonResult.setErrorMessage("验证码无效");
				return jsonResult;
			}
			member = getMember();
			member.setEmail(email);
			memberService.merge(member);
			setVerified(false);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("绑定邮箱异常：", e);
			jsonResult.setErrorMessage("绑定失败，请联系管理员");
		}
		return jsonResult;
	}
	
}
